<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['scll:form:edit']"
        >领料</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['scll:form:edit']"
        >查看</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="formList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="scllId" />
      <el-table-column label="领料单号" align="center" prop="lldh" />
      <el-table-column label="领料单状态" align="center" prop="lldState" :formatter="isStatus"/>
      <el-table-column label="生产工单编码" align="center" prop="gdCode" />
      <el-table-column label="负责人" align="center" prop="principal" />
      <el-table-column label="申请人" align="center" prop="proposer" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.lldState==0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['scll:form:edit']"
          >领料</el-button>

          <el-button
            v-if="scope.row.lldState==2"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateStatus(scope.row)"
            v-hasPermi="['scll:form:edit']"
          >审核</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="getLld(scope.row)"
            v-hasPermi="['scll:form:remove']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产领料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
        <el-table :data="lldData" style="width: 100%">
          <el-table-column prop="index" label="序号" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="wlCode" label="物料编码" width="150"/>
          <el-table-column prop="wlName" label="物料名称" width="100"/>
          <el-table-column prop="wlGg" label="物料规格" width="100"/>
          <el-table-column prop="dwName" label="单位" width="80"/>
          <el-table-column prop="getNum" label="申请数量" width="80"/>
          <el-table-column label="出库仓库" prop="ckName" width="130">
            <template scope="scope">
              <el-input v-model="scope.row.ckName" placeholder="请输入" readonly
                        @click.native="getHouses(scope.row,scope.$index)" suffix-icon="el-icon-more"/>
            </template>
          </el-table-column>
          <el-table-column prop="itemGrade" label="物料等级" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.wlLevel" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dispatchedQuantity" label="出库数量" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.ckNum" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
        </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 仓库弹框 -->
    <el-dialog title="选择仓库" :visible.sync="selectCk" width="30%">
      <el-container>
        <el-main>
          <!-- 展示仓库信息 -->
          <el-table border :data="warehouses" @row-dblclick="updateCk">
            <el-table-column prop="ckCode" label="仓库编码"/>
            <el-table-column prop="ckName" label="仓库名称"/>
          </el-table>
        </el-main>
      </el-container>
    </el-dialog>

    <!--查看领料单弹窗-->
    <el-dialog title="物料需求" :visible.sync="lldSelected" width="870px"  append-to-body>
      <div class="dialog-content" style="height: 600px">
        <el-table :data="lldhlist" style="width: 100%">
          <el-table-column prop="" label="序号" width="50" >
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="wlCode" label="物料编码" width="120" />
          <el-table-column prop="wlName" label="物料名称"  />
          <el-table-column prop="wlGg" label="物料规格"  />
          <el-table-column prop="dwName" label="单位" />
          <el-table-column prop="sclldGetNum" label="申请数量"  />
          <el-table-column prop="ckName" label="出库仓库"  />
          <el-table-column prop="scllGetNum" label="出库数量"  />
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="lldSelected=false">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listForm,
  getForm,
  delForm,
  addForm,
  updateForm,
  getLldList,
  getCk,
  getLl,
  getAuditMaterial, getLldh
} from "@/api/scll/form";

export default {
  name: "Form",
  data() {
    return {
      lldData:[{

      }],
      //领料单列表
      lldhlist:[],
      lldDataList:[],
      //查看领料单
      lldSelected:false,
      currentRow: null ,// 用于保存当前选中的行
      //显示仓库弹窗
      selectCk:false,
      //选中行下标
      selectedIndex:null,
      form: {
        items: Array(12).fill({
          itemCode: '',
          itemName: '',
          itemSpecification: '',
          unit: '',
          requestedQuantity: '',
          warehouse: '',
          itemGrade: '',
          dispatchedQuantity: ''
        })
      },
      warehouses:[],
      // 遮罩层
      loading: true,
      //领料单的id:
      scllId:null,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedScllMaterialRequiredRescord: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产领料表格数据
      formList: [],
      //领料单号
      lldhF:null,
      // 生产领料所需物料表格数据
      scllMaterialRequiredRescordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        lldh: null,
        lldState: null,
        gdCode: null,
        principal: null,
        proposer: null,
        applicationTime: null
      },
      // 表单参数
      // form: {},
      // 表单校验
      rules: {
        lldh: [
          { required: true, message: "领料单号不能为空", trigger: "blur" }
        ],
        lldState: [
          { required: true, message: "领料单状态 1.已经领料 0.未领料不能为空", trigger: "blur" }
        ],
        gdCode: [
          { required: true, message: "生产工单编码不能为空", trigger: "blur" }
        ],
        principal: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        proposer: [
          { required: true, message: "申请人不能为空", trigger: "blur" }
        ],
        applicationTime: [
          { required: true, message: "申请时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询生产领料列表 */
    getList() {
      this.loading = true;
      listForm(this.queryParams).then(response => {
        this.formList = response.rows;
        this.total = response.total;
        console.log(this.formList)
        this.loading = false;
      });
    },
    //选中仓库
    updateCk(row){
      if (this.selectedIndex !== null) {
        let obj = {};
        obj.wlName=this.lldData[this.selectedIndex].wlName;
        obj.wlCode=this.lldData[this.selectedIndex].wlCode;
        obj.wlGg=this.lldData[this.selectedIndex].wlGg;
        obj.proposer=this.lldData[this.selectedIndex].proposer;
        obj.lldh=this.lldData[this.selectedIndex].lldh;
        obj.llId=this.lldData[this.selectedIndex].llId;
        obj.getNum=this.lldData[this.selectedIndex].getNum;
        obj.dwName=this.lldData[this.selectedIndex].dwName;
        obj.wlLevel=this.lldData[this.selectedIndex].wlLevel;
        obj.ckNum=this.lldData[this.selectedIndex].ckNum;
        obj.ckCode =row.ckCode;
        obj.ckName=row.ckName;
        this.lldData.splice(this.selectedIndex,1);
        this.lldData.splice(this.selectedIndex,0,obj);
        this.selectCk = false;
        console.log("res:"+JSON.stringify(this.lldData[this.selectedIndex]));
      }

    },
    /**
     * 判断领料状态
     * */
    isStatus(row, column, cellValue){
      if (cellValue=="1"){
        return "已领料";
      }else if(cellValue=="0"){
        return "未领料";
      }else{
        return "待审核";
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.lldDataReset();
    },
    // 表单重置
    reset() {
      this.form = {
        scllId: null,
        lldh: null,
        lldState: null,
        gdCode: null,
        principal: null,
        proposer: null,
        applicationTime: null
      };
      this.scllMaterialRequiredRescordList = [];
      this.resetForm("form");
    },
    getHouses(row,rowIndex){
      this.selectedIndex=rowIndex;
      this.currentRow = row; // 设置当前选中的行
      const wlCode=row.wlCode;
      console.log(rowIndex);
      this.selectCk=true;
      getCk(wlCode).then(response=>{
        this.warehouses=response.data;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scllId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产领料";
    },

    /**审核按钮操作*/
    updateStatus(row){
      const scllId=row.scllId;
      getAuditMaterial(scllId).then(response=>{
        this.$modal.msgSuccess("领料审核成功");
        this.getList();
      })
    },

    /** 领料按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lldh = row.lldh;
      this.scllId=row.scllId;
      this.lldhF=row.lldh;
      console.log(lldh)
      getLldList(lldh).then(response => {
        this.lldData = response.data;
        // console.log(this.lldData);
        // this.lldData.map(row=>{
        //   row.ckName='000';
        //   row.ckCode=null;
        // })
        this.open = true;
      });
    },
    lldReset(){
      this.lldData=[{ckCode:null,ckName:null}]
    },
    /** 提交按钮 */
    submitForm() {
      let isValid = true;

     for (let item of this.lldData){
       if (!item.ckName) {
         this.$message.error(`仓库不能为空`);
         isValid = false;
         return;
       }
       if (!item.wlLevel) {
         this.$message.error(`物料等级不能为空`);
         isValid = false;
         return;
       }
       // if (item.ckNum === 0||item.ckNum!="") {
       //   this.$message.error(`出库数量不能为空`);
       //   console.log(item.ckNum)
       //   isValid = false;
       //   return;
       // }
       if (item.ckNum > item.getNum) {
         this.$message.error(`出库数量不能大于申请数量`);
         isValid = false;
         return;
       }
     }


      if (isValid) {
        console.log('表单验证通过', this.lldData);
        let scllMaterialRequiredRescords=this.lldData.map(row=>{
          return{
            scllId:this.scllId,
            wlCode:row.wlCode,
            llCode:null,
            llslLevel:null,
            getNum:row.ckNum,
            ckCode:row.ckCode,
            lldh:this.lldhF
          }
        })
        console.log(scllMaterialRequiredRescords);
        getLl(scllMaterialRequiredRescords).then(response=>{
          this.$modal.msgSuccess("领料单提交成功");
          this.open=false;
          this.lldDataReset()
          this.getList();
        })
      }
    },
    lldDataReset(){
      this.lldData=[];
    },
    /**查看领料单*/
    getLld(row){
      this.lldSelected=true;
      const lldh=row.lldh;
      console.log(lldh)
      getLldh(lldh).then(response=>{
        this.lldhlist=response.data;
        console.log(this.lldhlist);
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scllIds = row.scllId || this.ids;
      this.$modal.confirm('是否确认删除生产领料编号为"' + scllIds + '"的数据项？').then(function() {
        return delForm(scllIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 生产领料所需物料序号 */
    rowScllMaterialRequiredRescordIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 生产领料所需物料添加按钮操作 */
    handleAddScllMaterialRequiredRescord() {
      let obj = {};
      obj.wlCode = "";
      obj.getNum = "";
      obj.ckCode = "";
      this.scllMaterialRequiredRescordList.push(obj);
    },
    /** 生产领料所需物料删除按钮操作 */
    handleDeleteScllMaterialRequiredRescord() {
      if (this.checkedScllMaterialRequiredRescord.length == 0) {
        this.$modal.msgError("请先选择要删除的生产领料所需物料数据");
      } else {
        const scllMaterialRequiredRescordList = this.scllMaterialRequiredRescordList;
        const checkedScllMaterialRequiredRescord = this.checkedScllMaterialRequiredRescord;
        this.scllMaterialRequiredRescordList = scllMaterialRequiredRescordList.filter(function(item) {
          return checkedScllMaterialRequiredRescord.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleScllMaterialRequiredRescordSelectionChange(selection) {
      this.checkedScllMaterialRequiredRescord = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('scll/form/export', {
        ...this.queryParams
      }, `form_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
